//
//  AppDelegate+PushService.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/25.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "AppDelegate+PushService.h"
#import "JPUSHService.h"
#import "PushHelper.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate (PushService)
-(void)initAPNsWithLaunchOptions:(NSDictionary *)launchOptions{
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    } else {//可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert)categories:nil];
    }
    //0 (默认值)表示采用的是开发证书，1 表示采用生产证书发布应用。
    [JPUSHService setupWithOption:launchOptions appKey:JPUSHAPPKEY
                          channel:JPUSHCHANNEL
                 apsForProduction:ISAPPPRODUCT
            advertisingIdentifier:nil];
    // 注册通知（需要自定义消息时使用）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMessage:)name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    //    NSDictionary *userInfo = [notification userInfo];
    //    NSString *title = [userInfo valueForKey:@"title"];
    //    NSString *content = [userInfo valueForKey:@"content"];
    //    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    //
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    //    LGFLog(@"接受到自定义消息 %@",userInfo);
    //    [PushHelper handlePushMessageActiveWithUserInfo:userInfo];
    ////    self.timeLabel.text = [NSString stringWithFormat:@"时间：%@", [dateFormatter stringFromDate:[NSDate date]]];
    //    self.titleLabel.text = [NSString stringWithFormat:@"标题：%@", title];
    //    self.contentLabel.text = [NSString stringWithFormat:@"内容：%@", content];
    //    self.extraLabel.text = [NSString stringWithFormat:@"传值：%@", [self logDic:extra]];
}

//后台运行
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

//- (void)networkDidReceiveMessage:(NSNotification *)notification{
//    LGFLog(@"收到消息");
//    NSDictionary *userInfo = [notification userInfo];
//    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationJpushDidReceive object:nil userInfo:userInfo];
//}

//注册APNs成功并上报DeviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

//实现注册APNs失败接口
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    LGFLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support//前台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    LGFLog(@"前台收到通知");
    lNOTIF_POST(receivePushMessageSuccessNoti, nil);
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0){
            [PushHelper handlePushMessageActiveWithUserInfo:userInfo];
        }
    }
    else {
        // 判断为本地通知
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

// iOS 10 Support//后台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    lNOTIF_POST(receivePushMessageSuccessNoti, nil);
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    LGFLog(@"后台收到通知");
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //后台
        [PushHelper handlePushMessageBackgroundWithUserInfo:userInfo];
    }
    completionHandler();
}

@end
